const express = require('express')
const Result = require('../models/Result')
const { login, findUser } = require('../services/user')
const { md5, decoded } = require('../utils')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const jwt = require('jsonwebtoken')

const router = express.Router()

// 创建登录的请求接口
router.post(
	'/login',
	[
		// 对用户名和密码进行校验
		body('username').isString().withMessage('用户名必须为字符'),
		body('password').isString().withMessage('密码必须为数字')
	],
	function(req, res, next) {
		// 获取错误信息
		const err = validationResult(req)
		if(!err.isEmpty()) {
			const [{ msg }] = err.errors
			next(boom.badRequest(msg))
		} else {
			// console.log(req.body)
			// 获取用户的请求内容
			let { username, password } = req.body
			console.log(username, password)
			// 对密码进行md5加密
			password = md5(`${password}${PWD_SALT}`)
			login(username, password).then(user => {
				if(!user || user.length === 0) {
					new Result('登录失败').fail(res)
				} else {
					// 生成token
					const token = jwt.sign(
						{ username },
						PRIVATE_KEY,
						{ expiresIn: JWT_EXPIRED }
					)
					new Result({ token } , '登录成功').success(res)
				}
			})
		}
})

router.get('/info', function(req, res) {
	const decode = decoded(req)
	if(decode && decode.username) {
			// 获取用户信息
		findUser(decode.username).then(user => {
			console.log(user)
			if(user) {
				user.roles = [user.role]
				new Result(user, '用户信息查询成功').success(res)
			} else {
				new Result('用户信息查询失败').fail(res)
			}
		})
	} else {
		new Result('用户信息查询失败').fail(res)
	}
})

module.exports = router